$(document).ready(function (){
require(['inputdrop',
	     'tree',
	     'tab',
	     'plot',
	     'workorder',
	     'event'] ,function (inputdrop ,tree ,tab ,plot ,workorder,pevent){

	$("#content_div").addClass("appbgf");

	var el_search_div = $("[class*=search-div]");

	var el_ul = el_search_div.find("ul");

	var search_el;

	var searchObj = {stateId:1};

	var vagueObj = new Object();

	var vagueFlag = false;

	event_init();

	var el_event_list = $("#table_div");

	pevent.secEventList();

	var condition_map = new HashMap();
	condition_map.put("eventName" ,{name:"事件名称"});
	condition_map.put("alarmName" ,{name:"应用事件名称"});
	condition_map.put("deviceType" ,{name:"发生源设备类型" ,render : function (){
		return inputdrop.getText($("#deviceType"));
	}});
	condition_map.put("levelId" ,{name:"等级" ,render : function (txt){
		var buffer = [];
		txt = txt.split(",");
		for (var i = 0; i < txt.length; i++) {
			buffer.push(event_level_id_text[txt[i]]);
		}
		return buffer.join(",");
	}});
	condition_map.put("startDate" ,{name:"聚合开始起始时间"});
	condition_map.put("endDate" ,{name:"聚合开始终止时间"});
	condition_map.put("startDate1" ,{name:"聚合结束起始时间"});
	condition_map.put("endDate1" ,{name:"聚合结束终止时间"});
	condition_map.put("stateId" ,{name:"状态" ,render : function (txt){
		var buffer = [];
		txt = txt.split(",");
		for (var i = 0; i < txt.length; i++) {
			buffer.push(event_state_id_text[txt[i]]);
		}
		return buffer.join(",");
	}});
	condition_map.put("kindId" ,{name:"类型" ,render : function (txt){
		return inputdrop.getText($("#kindId"));
	}});
	condition_map.put("sourceStartip" ,{name:"源IP起始"});
	condition_map.put("sourceEndip" ,{name:"源IP结束"});
	condition_map.put("sourceIpv6" ,{name:"源IPV6"});
	condition_map.put("destStartip" ,{name:"目的IP起始"});
	condition_map.put("destEndip" ,{name:"目的IP结束"});
	condition_map.put("destIpv6" ,{name:"目的IPV6"});
	condition_map.put("occurStartip" ,{name:"发生源IP起始"});
	condition_map.put("occurEndip" ,{name:"发生源IP结束"});
	condition_map.put("occurIpv6" ,{name:"发生源IPV6"});
	condition_map.put("securityName" ,{name:"管控域"});

	

	function event_init()
	{
		//模糊查询
		$(".vague-btn").click(function(){
			if($("#vague_div").val() == "")
			{
				g_dialog.operateAlert($("#table_oper"),"请输入关键词。","error");
				return false;
			}
			vagueFlag = true;
			vagueObj = {searchFlag:"1" ,keyWords:$('#vague_div').val()};
			pevent.secEventList({pObj:vagueObj});
		})

		//自定义列
		$("[id=custom_btn]").click(function (){
			pevent.eventCustomCol($(this) ,{
				tplUrl : "module/event_alarm/sec_event_analy_tpl.html",
				colQueryUrl : "siem/securityWatchEvent/querySecEventColumeIds",
				customColumnsUrl : "siem/securityWatchEvent/saveCustomColumn",
				type:"1",
				cbf : function (){
					pevent.secEventList({
						searchObj : searchObj
					});
					$("#grid_btn").hide();
					$("#count_btn").show();
				}
			});
		});

		// 生成工单
		$("#order_btn").click(function (){
			pevent.createWorkOrder({
				gridEl : $("#table_div"),
				eventIdKey : "eventId",
				eventTypeVal : "1"
			});
		});

		//忽略全部
		$("#lgnore_all_btn").click(function(rowData) {
			var data = g_grid.getData($("#table_div") ,{chk:false});
			if (data.length == 0)
			{
				// 弹出提示
				g_dialog.operateAlert($("#table_div") ,"列表无数据。" ,"error");
				// 直接返回
				return false;
			}
			var queryObj = searchObj;
			pevent.ignoreAll({
				gridEl: el_event_list,
				lgnore_all_url: "siem/securityWatchEvent/doIgnoreAll",
				queryObjStr : queryObj,
				cb: function() {
					pevent.secEventList();
				}
			});
		});

		//忽略
		$("#lgnore_btn").click(function (rowData){
			var array = g_grid.getIdArray(el_event_list ,{chk:true ,attr:"stateId"});
			if (array.join("").indexOf("2") >= 0)
			{
				g_dialog.operateAlert(el_event_list ,"选中记录中包含已忽略的记录，请重新选择","error");
				return false;
			}
			pevent.ignore({
				gridEl: el_event_list,
				attr: "eventId",
				ignoreType : "sync",
				ignore_url: "siem/securityWatchEvent/doIgnore",
				cb: function() {
					g_grid.refresh(el_event_list);
				}
			});
		});

		//导出EXCEL
		$("#export_btn").click(function (rowData){
			var queryObj = searchObj;
			pevent.eventExport({
				attr : "eventId",
				url : "siem/securityWatchEvent/exportSecurity",
				nocol : true,
				queryObjStr : JsonTools.encode(queryObj)
			});
		});

		//统计
		$("#count_btn").click(function (){
			//切换到统计图展示
			if(vagueFlag && vagueObj) {
				searchObj = vagueObj;
				vagueFlag = false;
			}
			count_table_init();
			$(this).toggle();
			$("#grid_btn").toggle();
			$("#table_div").css("height" ,"auto")
		});
		$("#grid_btn").click(function (){
		   //切换到列表展示
			pevent.secEventList({
				searchObj:searchObj
			});
			$(this).toggle();
			$("#count_btn").toggle();
		});
		//查询
		$("#search_btn").click(function(){
			if (search_el)
			{
				search_el.parent().show();
				return false;
			}
			search_tpl_init();
		});

		el_ul.on("click" ,"[class=icon-remove]" ,function (){
			delete searchObj[$(this).attr("data-key")];
			$(this).closest("li").remove();
			if (el_ul.find("li").size() == 0)
			{
				el_search_div.hide();
			}
			g_grid.refresh($("#table_div"),{
				queryBefore : function(queryObj){
					return searchObj;
				}
			});
		})

		index_list_search_render($("um-search") ,{
			cbf : function (val){
				g_grid.refresh($("#table_div") ,{
					paramObj : {eventName : val}
				})
			},
			placeholder : "请输入事件名称"
		})

		g_formel.list_filter_render($("um-filter") ,{
			condition : [
							{text : "状态" ,name : "stateId" ,data : [{text:"未处理",value:"1"} ,{text:"忽略",value:"2"},
																		 {text:"处理中",value:"3"} ,{text:"已处理",value:"4"}]}
						],
			click : function (paramObj){
				g_grid.refresh($("#table_div") ,{
					paramObj : paramObj
				})
			}
		})
	}

	function count_table_init()
	{
		var sec_event_stat_url = "siem/securityWatchEvent/statQuery";
		el_event_list.html("");
		$.ajax({
			type: "GET",
			url: "module/event_alarm/sec_event_analy_tpl.html",
			success :function(data)
			{
				el_event_list.html($(data).find("[id=count_tem]"));
				chart_render(el_event_list.find("[id=eventname_analy_chars]"), 1 ,"安全事件统计" ,sec_event_stat_url);
				chart_render(el_event_list.find("[id=type_analy_chars]"), 2 ,"安全事件统计" ,sec_event_stat_url);
				chart_render(el_event_list.find("[id=srcIp_analy_chars]"), 3 ,"安全事件统计" ,sec_event_stat_url);
				chart_render(el_event_list.find("[id=destIp_analy_chars]"), 4 ,"安全事件统计" ,sec_event_stat_url);
				chart_render(el_event_list.find("[id=level_analy_chars]"), 6 ,"安全事件统计" ,sec_event_stat_url);
				chart_render(el_event_list.find("[id=time_analy_chars]"), 7 ,"安全事件统计" ,sec_event_stat_url);
				chart_render(el_event_list.find("[id=device_analy_chars]"), 8 ,"安全事件统计" ,sec_event_stat_url);
				chart_render(el_event_list.find("[id=deviceType_analy_chars]"), 9 ,"安全事件统计" ,sec_event_stat_url);

			}
		});
	}

	function search_tpl_init()
	{
		$.ajax({
			type: "GET",
			url: "module/event_alarm/sec_event_analy_tpl.html",
			success: function(data) {
				g_dialog.dialog($(data).find("[id=query_template]"), {
					width: "900px",
					title:"安全事件查询",
					init:init,
					autoHeight:"autoHeight",
					closeType:"hide",
					saveclick: save_click
				});
			}
		});

		function init(el)
		{
			search_el = el;
			g_validate.init(el);
			g_formel.code_list_render({
		   	   	key : "deviceAssetTypeSiemTree",
				deviceTypeEl : el.find("[id=deviceType]"),
				onlyLastChild:false
			});
			var startday = g_moment().add(-1,'days').format('YYYY-MM-DD HH:mm:ss');
			var today = g_moment().format('YYYY-MM-DD HH:mm:ss');
			// el.find("[data-id=startDate]").val(startday);
			// el.find("[data-id=endDate]").val(today); 
			// el.find("[data-id=startDate1]").val(startday);
			// el.find("[data-id=endDate1]").val(today); 
			//change函数
			el.find("[id=startDateRange]").change(function(){
				var range = $(this).val();
				datechange({
					range:range,
					startDate:el.find("[data-id=startDate]"),
					endDate:el.find("[data-id=endDate]")
				});
			});
			el.find("[id=endDateRange]").change(function(){
				var range = $(this).val();
				datechange({
					range:range,
					startDate:el.find("[data-id=startDate1]"),
					endDate:el.find("[data-id=endDate1]")
				});
			});
			el.find("[data-id=stateId]").change(function(){
				var tmp;
				if ($(this).val() != null) 
				{
					tmp = $(this).val().join(",");
					if(tmp.indexOf("2") > -1)
					{
						el.find("[data-id=ignoreState]").removeAttr("disabled");
					}
					else
					{
						el.find("[data-id=ignoreState]").attr("disabled","disabled");
						el.find("[data-id=ignoreState]").val("");
					}
				}
				
				el.find("[data-id=ignoreState]").trigger("change");
			});
			g_formel.code_list_render({
		   	   	key : "secEventCtg",
				secEventTypeElMul : el.find("[id=kindId]")
			});

			var el_startSrcIp = el.find("[data-id=sourceStartip]");
			var el_endSrcIp = el.find("[data-id=sourceEndip]");
			var el_srcIpv6 = el.find("[data-id=sourceIpv6]");
			var el_startDestIp = el.find("[data-id=destStartip]");
			var el_endDestIp = el.find("[data-id=destEndip]");
			var el_destIpv6 = el.find("[data-id=destIpv6]");
			var el_startDeviceIp = el.find("[data-id=occurStartip]");
			var el_endDeviceIp = el.find("[data-id=occurEndip]");
			var el_deviceIpv6 = el.find("[data-id=occurIpv6]");

			el.find("[name=srcIpType]").click(function(){
				var type = $(this).val();
				if (type == 1) 
				{
					el_startSrcIp.removeAttr("disabled");
					el_endSrcIp.removeAttr("disabled");
					el_srcIpv6.attr("disabled","disabled");
					el_srcIpv6.val("");
				}
				else
				{
					el_startSrcIp.attr("disabled","disabled");
					el_endSrcIp.attr("disabled","disabled");
					el_srcIpv6.removeAttr("disabled");
					el_startSrcIp.val("");
					el_endSrcIp.val("");
				}
				g_validate.clear([el_startSrcIp,el_endSrcIp,el_srcIpv6]);
			});
			el.find("[name=destIpType]").click(function(){
				var type = $(this).val();
				if (type == 1) 
				{
					el_startDestIp.removeAttr("disabled");
					el_endDestIp.removeAttr("disabled");
					el_destIpv6.attr("disabled","disabled");
					el_destIpv6.val("");
				}
				else
				{
					el_startDestIp.attr("disabled","disabled");
					el_endDestIp.attr("disabled","disabled");
					el_destIpv6.removeAttr("disabled");
					el_startDestIp.val("");
					el_endDestIp.val("");
				}
				g_validate.clear([el_startDestIp,el_endDestIp,el_destIpv6]);
			});
			el.find("[name=occurIpType]").click(function(){
				var type = $(this).val();
				if (type == 1) 
				{
					el_startDeviceIp.removeAttr("disabled");
					el_endDeviceIp.removeAttr("disabled");
					el_deviceIpv6.attr("disabled","disabled");
					el_deviceIpv6.val("");
				}
				else
				{
					el_startDeviceIp.attr("disabled","disabled");
					el_endDeviceIp.attr("disabled","disabled");
					el_deviceIpv6.removeAttr("disabled");
					el_startDeviceIp.val("");
					el_endDeviceIp.val("");
				}
				g_validate.clear([el_startDeviceIp,el_endDeviceIp,el_deviceIpv6]);
			});
			
		}

		function save_click(el,saveObj)
		{
			if(!g_validate.validate(el))
			{
				return false;
			}
			if (el.find("[name=srcIpType]:checked").val() == 1)
			{
				if (!g_validate.ipValidate(el.find("[data-id=sourceStartip]") ,el.find("[data-id=sourceEndip]")))
				{
					return false;
				}
			}
			if (el.find("[name=destIpType]:checked").val() == 1)
			{
				if (!g_validate.ipValidate(el.find("[data-id=destStartip]") ,el.find("[data-id=destEndip]")))
				{
					return false;
				}
			}
			if (el.find("[name=occurIpType]:checked").val() == 1)
			{
				if (!g_validate.ipValidate(el.find("[data-id=occurStartip]") ,el.find("[data-id=occurEndip]")))
				{
					return false;
				}
			}
			if (saveObj.levelId != null) 
			{
				saveObj.levelId = saveObj.levelId.join(",");
			}
			if (saveObj.stateId != null) 
			{
				saveObj.stateId = saveObj.stateId.join(",");
			}
			if ($("#table_div").find("[id=count_tem]").size() == 1) 
			{
				count_table_init();
			}
			else
			{
				// g_grid.refresh($("#table_div"),{
				// 	queryBefore : function(queryObj){
				// 		paramObj : {faultName : val}
				// 	}
				// });
				g_grid.refresh($("#table_div") ,{
					paramObj : saveObj
				})
			}
			g_dialog.hide(el, "hide");
			searchObj = saveObj;
			//query_conditon_render();
		}
	}
	function datechange(opt)
	{
		var range = opt.range;
		var startday;
		var today = g_moment().format('YYYY-MM-DD HH:mm:ss');
		if (range == 1) 
		{
			startday = g_moment().add(-1,'days').format('YYYY-MM-DD HH:mm:ss');
		}
		//最近一周
		else if (range == 2) 
		{
			startday = g_moment().add(-7,'days').format('YYYY-MM-DD HH:mm:ss'); 
		}
		//最近一月
		else if (range == 3) 
		{
			startday = g_moment().add(-30,'days').format('YYYY-MM-DD HH:mm:ss'); 
		}
		//最近一季度
		else if (range == 4) 
		{
			startday = g_moment().add(-90,'days').format('YYYY-MM-DD HH:mm:ss'); 
		}
		//最近一年
		else if (range == 5) 
		{
			startday = g_moment().add(-365,'days').format('YYYY-MM-DD HH:mm:ss'); 
		}
		opt.startDate.val(startday);
		opt.endDate.val(today);
	}

	function chart_render(el, typeid ,seriesName ,url) {
		var paramObj = new Object();
		paramObj = $.extend(paramObj, searchObj);
		paramObj.queryFlag = true;
		paramObj.typeid = typeid;
		// if (!paramObj.currentStatus || paramObj.currentStatus == "-1")
		// {
		// 	paramObj.currentStatus = 0;
		// }
		if (typeid == "7")
		{
			um_ajax_get({
				url: url,
				paramObj: paramObj,
				maskObj: el,
				successCallBack: function(data) {
					var seriesArray = [];
					var categoryArray = [];
					seriesObj = new Object();
					seriesObj.name = seriesName;
					seriesObj.type = "line";
					//seriesObj.areaStyle = {normal: {}};
					seriesObj.data = [];
					for (var i = 0; i < data.length; i++) {
						categoryArray.push(data[i].lable);
						seriesObj.data.push(data[i].value);
					}
					seriesArray.push(seriesObj);
					plot.lineRender(el, {
						category: categoryArray,
						series: seriesArray,
						grid: {
					        left: '6%',
					        right: '9%',
					        bottom: '3%',
					        containLabel: true
					    }
					});
				}
			});
		}
		else
		{
			var color_array = ['#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'];
			um_ajax_get({
				url: url,
				paramObj: paramObj,
				maskObj: el,
				successCallBack: function(data) {
					var seriesArray = [];
					var seriesObj = new Object();
					seriesObj.name = "值";
					seriesObj.type = "bar";
					seriesObj.data = [];
					seriesObj.itemStyle = new Object();
					seriesObj.itemStyle.normal = new Object();
					seriesObj.itemStyle.normal.color = color_array[typeid];
					var categoryArray = [];
					for (var i = 0; i < data.length; i++) {
						seriesObj.data.push(data[i].value);
						categoryArray.push(data[i].lable);
					}
					seriesArray.push(seriesObj);
					plot.barRender(el, {
						category: categoryArray,
						series: seriesArray,
						isVercital: true
					});
				}
			});
		}
	}

	function query_conditon_render()
	{
		var buffer = [];
		var condition_keys = Object.keys(searchObj);
		var tmp_key;
		var showFlag = false;
		var tmp_msg;
		var val_txt;
		for (var i = 0; i < condition_keys.length; i++) {
			tmp_key = condition_keys[i];
			if (searchObj[tmp_key] && condition_map.get(tmp_key))
			{
				val_txt = searchObj[tmp_key];
				condition_map.get(tmp_key).render && (val_txt = condition_map.get(tmp_key).render(val_txt))
				tmp_msg = condition_map.get(tmp_key).name+':'+val_txt;
				buffer.push('<li>');
				buffer.push('<div class="search-condition">');
				buffer.push('<span title="'+tmp_msg+'">'+tmp_msg+'</span>');
				buffer.push('</div><i class="icon-remove" data-key='+tmp_key+'></i>')
				buffer.push('</li>');
				showFlag = true;
			}
			
		}
		el_ul.html(buffer.join(""));
		showFlag && el_search_div.show();
		!showFlag && el_search_div.hide();
	}
});
});